import React, { Component, createRef } from 'react'
import PropTypes from "prop-types"
import { Form, Select, Input } from "antd"
/**
 * 添加分类的form组件
 */
const Item = Form.Item;
const Option = Select.Option
export default class AddForm extends Component {
    constructor(props) {
        super(props);
        // 创建一个 ref
        this.formRef = createRef();
    }

    //对props的值进行限制
    static propTypes = {
        categorys: PropTypes.array.isRequired,  //一级分类的数组
        parentId: PropTypes.string.isRequired,   //父分类的id
        setForm: PropTypes.func.isRequired    //用来传递form对象实例的函数
    }

    setValues = () => {
        const formInstance = this.formRef.current;
        const { parentId } = this.props;
        if (formInstance) {
            formInstance.setFieldsValue({
                parentId: parentId
            });
        }
    }
    //放在update生命周期的里面更新form的表单的数据
    componentDidUpdate() {
        this.setValues()
    }

    componentDidMount() {
        const formInstance = this.formRef.current;
        if (formInstance) {
            //将form对象通过setForm()传递父组件
            this.props.setForm(formInstance)
        }
    }

    render() {
        const { categorys, parentId } = this.props
        return (
            <Form name="addForm" style={{ maxWidth: 360 }} ref={this.formRef}
                initialValues={{
                    categoryName: '',
                    parentId: parentId
                }}>
                <Item label="分类等级" name='parentId' rules={[
                    {
                        required: true,
                        message: '请选择需要的分类等级!',
                    },
                ]}>
                    <Select placeholder="请选择分类">
                        <Option value='0'>一级分类</Option>
                        {
                            categorys.map(n => <Option key={n._id} value={n._id}>{n.name}</Option>)
                        }
                    </Select>
                </Item>

                <Item label="分类名称" name="categoryName" rules={[
                    {
                        required: true,
                        message: '请输入分类的名称!',
                    },
                ]} >
                    <Input placeholder='请输入分类的名称'></Input>
                </Item>
            </Form>
        )
    }
}


